// pages/user/page/master/achievement/collection/collection.js
const app = getApp();
const informationDB=wx.cloud.database().collection('staffInformationData')
import * as echarts from '../../../../../ec-canvas/echarts'

function getOption(xData, data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num) {
  var option = {
    color: ['#37a2da', '#32c5e9', '#67e0e3','#d57000','#006699','#e5323e'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: (params) => {
        if (!params.length) return ''
        let s = params[0].axisValueLabel+'\n'
        for (const iterator of params) {
          // 如果是负数则反转
          let d = iterator.data < 0 ? -iterator.data : iterator.data
          s += iterator.seriesName + '：' + d + '\n'
        }
        return s
      },
      confine: true
    },
    legend: {
      data: ['推拿平均销售额', '药品平均销售额', '副业平均销售额','推拿销售数量', '药品销售数量', '副业销售数量']
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [
      {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666',
          formatter: (value) => {
            // 负数取反 显示的就是正数了
            if (value < 0) return -value
            else return value
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: xData,//['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'],
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: '推拿平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data: data_tuina_sum,//[300, 270, 340, 344, 300, 320, 310],
        itemStyle: {
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }, {
        name: '推拿销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left',formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
          }
        },
        data:data_tuina_num,// [-30, -27, -34, -34, -30, -32, -31],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      },
      {
        name: '药品平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data:data_medical_sum,// [300, 270, 340, 344, 300, 320, 310],
        itemStyle: {
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }, {
        name: '药品销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left',formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
          }
        },
        data:data_medical_num,// [-30, -27, -34, -34, -30, -32, -31],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      }, 
      {
        name: '副业平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data:data_sideline_sum,// [120, 102, 141, 174, 190, 250, 220],
        itemStyle: {
          // emphasis: {
          //   color: '#32c5e9'
          // }
        }
      },
     
     {
        name: '副业销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left'
            ,formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
        }
        },
        data:data_sideline_num,// [-20, -32, -21, -34, -90, -130, -110],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      }
    ]
  };
  return option;
}

let chartLine1


Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      onInit: function (canvas, width, height){
          //初始化echarts元素，绑定到全局变量，方便更改数据
          chartLine1 = echarts.init(canvas, null, {
              width: width,
              height: height
          });
          canvas.setChart(chartLine1);

          //可以先不setOption，等数据加载好后赋值，
          //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
          var xData = ['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'];  // x轴数据 自己写
          var option = getOption(xData);

          chartLine1.setOption(option);
      }},
    index: 3,
    ishidden:false,
    array: ['2018','2019', '2020', '2021'],
    txt_explain:"2021全体员工业绩汇总统计图",
    btn_download:"点击下载员工业绩表",
    fileUrl:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  getAchieve:function (phone) {
    let that = this
    wx.showLoading({
      title: '正在统计....',
    })
    let year = that.data.array[that.data.index]
    var sdata = year+"/01/00"
    var edata = year+"/12/32"
     wx.cloud.callFunction({
       name: 'getAchieveList',// 要调用的云函数名称
       data: {             // 传递给云函数的event参数
         Tid:phone,
         sDate:sdata,//"2021/01/00",
         eDate:edata//"2021/12/32"
       }
     }).then(res => {
         console.log(res.result.data)
         var xData=['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'];
         var data_tuina_sum =[0,0,0,0,0,0,0,0,0,0,0,0] 
         var  data_medical_sum=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_sideline_sum=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_tuina_num =[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_medical_num=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_sideline_num=[0,0,0,0,0,0,0,0,0,0,0,0]
         res.result.data.forEach((item,i)=>{
             let idx = parseInt(item.date.slice(5,7))-1
             let classify = item.goodsID.slice(0,1)
             let sum = item.unitPrice*item.salenum
            //  console.log(idx,classify,item.unitPrice,item.salenum)
             if(classify=='T'){
               data_tuina_sum[idx] += sum
               data_tuina_num[idx] -= item.salenum
             }else if(classify=='M'){
               data_medical_sum[idx] += sum
               data_medical_num[idx] -= item.salenum
             }else{
               data_sideline_sum[idx] += sum
               data_sideline_num[idx] -= item.salenum
             }
         })
           data_tuina_sum.forEach((item,i)=>{
             data_tuina_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_tuina_num[i])).toFixed(2))
           })
           data_medical_sum.forEach((item,i)=>{
             data_medical_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_medical_num[i])).toFixed(2))
           })
           data_sideline_sum.forEach((item,i)=>{
             data_sideline_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_sideline_num[i])).toFixed(2))
         })
        //  console.log(data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num)
         // 方法一：
         var option = getOption(xData, data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num);
         //var option = getOption(xData, data_cur, data_his);
         //console.log(option)
         try {
          chartLine1.setOption(option);
         } catch (error) {
           console.log(error)
         }
         wx.hideLoading()
     })
  },
  onLoad: function (options) {
    //var phone = "15707254049"
    this.getAchieve()
  },
  bindPickerChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      ishidden:true
    })
  },
  clickSearch:function(e){
    let that = this
    let num =e.detail.value.famNum
    let year = that.data.array[that.data.index]
    if(num==''){
      wx.showToast({
        title: '请输入家庭编号',
        icon:'none'
      })
      that.getAchieve()
      that.setData({
        txt_explain:"2021全体员工业绩汇总统计图"
      })
    }else if(num.length==7){
      console.log(num.length)
      //staffInformationData
      informationDB.where({
        TechID:num
      }).get().then(res => {
          console.log(res.data[0])
          if(res.data[0]==undefined){
            wx.showToast({
              title: '没有找到该职工',
              icon:"none"
            })
        }else{
          that.setData({
            txt_explain:year+"年员工“"+res.data[0].TechName+"”业绩统计图"
          })
          that.getAchieve(res.data[0].TechPhone)
        }
      })
    }else if(num.length==11){
      informationDB.where({
        TechPhone:num
      }).get().then(res => {
          console.log(res.data[0])
          if(res.data[0]==undefined){
            wx.showToast({
              title: '没有找到该职工',
              icon:"none"
            })
        }else{
          that.setData({
            txt_explain:year+"年员工“"+res.data[0].TechName+"”业绩统计图"
          })
          that.getAchieve(num)
        }
      })
    }else{
        informationDB.where({
          TechName:num
        }).get().then(res => {
            console.log(res.data[0])
            if(res.data[0]==undefined){
                wx.showToast({
                  title: '没有找到该职工',
                  icon:"none"
                })
            }else{
              that.getAchieve(res.data[0].TechPhone)
              that.setData({
                txt_explain:year+"年员工“"+num+"”业绩统计图"
              })
            }
        })
    }
  },
  savaExcel(datalist) {
    let that = this
    console.log(datalist)
    wx.cloud.callFunction({
      name: "generateExcel",
      data: {
        datalist: datalist
      },
      success(res) {
        console.log("保存成功", res)
        that.getFileUrl(res.result.fileID)
      },
      fail(res) {
        console.log("保存失败", res)
      }
    })
  },

  clickDownload:function(e){
   
    // datalist
    let that = this
    if(that.data.btn_download=="点击下载员工业绩表"){
    console.log(e)
    wx.showLoading({
      title: '正在生成下载链接...',
    })
    wx.cloud.callFunction({
      name: "getStaffAchievemt",
      success(res) {
        // console.log("读取成功", res.result)
        
         that.savaExcel(res.result)
         wx.hideLoading({
           success: (res) => {
            that.setData({
              btn_download:"点击复制下载链接"
            })
           },
         })
      },
      fail(res) {
        console.log("读取失败", res)
      }
    })
  }else{
    wx.setClipboardData({
      data: that.data.fileUrl,
      success(res) {
        wx.getClipboardData({
          success(res) {
            that.setData({
              btn_download:"点击下载员工业绩表"
            })
            wx.showToast({
              title: '复制成功',
              icon:'success'
            })
            console.log("复制成功",res.data) // data
          }
        })
      }
    })
  }
  },
  getFileUrl(fileID) {
    let that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        // get temp file URL
        console.log("文件下载链接", res.fileList[0].tempFileURL)
        that.setData({
          fileUrl: res.fileList[0].tempFileURL
        })
      },
      fail: err => {
        // handle error
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(function () {
      // 获取 chart 实例的方式
      // console.log(chart)
    }, 3000);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})